package dgut.party.business.security;

import dgut.party.business.dao.user.AccountRepository;
import dgut.party.business.entity.base.Account;
import dgut.party.business.entity.rbac.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private AccountRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    List<Account> users = userRepository.findByUsernameJoinRoleAuthority(username);
    if (users.isEmpty() || users.size() > 1)
      throw new UsernameNotFoundException(username);
    Account user = users.get(0);
    if (user == null) {
      throw new UsernameNotFoundException(username);
    }
    if (!user.isEnabled()) {
      throw new UsernameNotFoundException(username + "已被停用");
    }

    Set<GrantedAuthority> authorities = new HashSet<>();
    for (Role role : user.getRoles()) {
      // 前端只获取角色信息
      authorities.add(new SimpleGrantedAuthority(role.getName()));
    }
    return new UserPrincipal(user.getId(), user.getUsername(), user.getPassword(),
      true, // enabled
      true, // accountNonExpired
      true, // credentialsNonExpired
      true, // accountNonLocked
      authorities);
  }

}
